package com.yanggu.zookeeper;

import org.apache.zookeeper.*;
import org.apache.zookeeper.data.ACL;
import org.apache.zookeeper.data.Stat;
import org.junit.Before;
import org.junit.Test;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @version V1.0
 * @author: YangGu
 * @date: 2020/2/9 17:53
 * @description:
 */
public class ZookeeperDemo {

    /**
     * 需要注意的是","的后面不能有空格
     */
    private final String connect = "localhost:2181";

    /**
     * 超时时间，单位为毫秒
     */
    private final int sessionTimeout = 2000;

    private ZooKeeper client;

    private ZooKeeper zk;

    /**
     * 初始化工作，获取操作客户端对象
     *
     * @throws Exception
     */
    @Before
    public void init() throws Exception {
        client = new ZooKeeper(connect, sessionTimeout, watchedEvent -> {
            System.out.println(watchedEvent);
            try {
                List<String> children = client.getChildren("/", true);
                for (String child : children) {
                    System.out.println(child);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }

    /**
     * 创建子节点(4中节点)
     *
     * @throws Exception
     */
    @Test
    public void create() throws Exception {
        String path = client.create("/yanggu", "yanggu".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
        System.out.println(path);
    }

    /**
     * 获取子节点并监听节点变化
     *
     * @throws Exception
     */
    @Test
    public void getChildrenAndWatch() throws Exception {
        //这里类似注册一个回调函数
        List<String> children = client.getChildren("/", watchedEvent -> {
            //监控到路径发生变化
            System.out.println(watchedEvent.getPath());
            //打印变化的类型
            System.out.println(watchedEvent.getType().name());
        });
        children.forEach(System.out::println);
        TimeUnit.SECONDS.sleep(Long.MAX_VALUE);
    }

    /**
     * 判断znode是否存在
     *
     * @throws Exception
     */
    @Test
    public void exist() throws Exception {
        Stat stat = client.exists("/idea", false);
        System.out.println(stat == null ? "不存在" : "存在");
    }
}
